import { useClipboard } from '@vueuse/core';
// @ts-ignore
import html2canvas from 'html2canvas';

import { NotifySuccess } from './notify';
import { i18nTranslate } from '../i18n';
/**
 * 加载assets/images目录下的图片
 * @param url
 * @returns
 */
export const getAssetsImage = (url: string) => {
  return new URL(`../assets/images/${url}`, import.meta.url).href;
};

/**
 * 加载 public 目录下的图片，可能需要针对本地和生产做不同路径配置
 * @param path
 * @returns
 */
export const getPublicImage = (path: string) => {
  return `/${path}`;
};

const { copy } = useClipboard({
  legacy: true,
});

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  copy(text)
    .then(() => {
      NotifySuccess(i18nTranslate('copy_success'));
    })
    .catch((err) => {
      console.error('copy failed:', err);
    });
};
/**
 * 对金额格式化
 * @param text
 */
export function formatCurrency(money: String | number, assetCode?: string) {
  if (money) {
    let handleNum = parseFloat(String(money));
    let isToFixed = false;
    if ((assetCode && ['USD', 'WT'].includes(assetCode)) || !assetCode) {
      money = Math.floor(Number(money) * 100) / 100;
    } else {
      isToFixed =
        handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > 8;
      if (isToFixed) {
        money = handleNum.toFixed(8);
      }
    }
    money = parseFloat(String(money));
    const numToString = `${money}`;
    let strFront = '';
    let strEnd = '';
    let meetPoint = false;
    for (let i = 0; i < numToString.length; i++) {
      if (numToString[i] == '.') {
        meetPoint = true;
      }
      meetPoint ? (strEnd += numToString[i]) : (strFront += numToString[i]);
    }
    let result = '';
    strEnd
      ? (result = `${strFront.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')}.${strEnd.replace(
          '.',
          '',
        )}`)
      : (result = strFront.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,'));
    return result;
  }
  return money;
}

/**
 * @param {element} el       截图的dom区域(通过ref获取打的dom)
 * @param {Object} options   插件的一些自定义配置
 * 注意：1、配置项官网地址： https://allenchinese.github.io/html2canvas-docs-zh-cn/docs/html2canvas-configuration.html
 *      2、获取dom的时候需要等待页面加载完成之后
 *      3、ignoreElements 方法会遍历所有节点，我这里给了一个id为clos的结点，因为不需要在截图中留下，就把该节点排除了.
 */
export function drawToPic(el: Element) {
  const width = parseInt(window.getComputedStyle(el).width);
  const height = parseInt(window.getComputedStyle(el).height);
  const cs = document.createElement('canvas');
  const scale = 1;
  cs.width = width * scale;
  cs.height = height * scale;

  const options = {
    useCORS: true,
    canvas: cs,
    scale: scale,
    ignoreElements: (element: Element) => element.id === 'clos',
  };
  html2canvas(<HTMLElement>el, options).then((canvas: any) => {
    const url = URL.createObjectURL(base64ToBlob(canvas.toDataURL('image/png')));
    downloadImage(url);
  });
}

// base64转blob
function base64ToBlob(code: any) {
  const parts = code.split(';base64,');
  const contentType = parts[0].split(':')[1];
  const raw = window.atob(parts[1]);
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
}
//下载图片
function downloadImage(url: any) {
  // 这里使用 img 是因为在客户端中，不能直接下载，要调用原生的方法
  const createImg = document.createElement('img');
  createImg.setAttribute('src', url);
  // 如果是在网页中可以直接创建一个 a 标签直接下载
  const a = document.createElement('a');
  a.href = url;
  //window.open(a.href) //测试时候使用，截图之后新开一个浏览器页面查看是否截图成功
  a.download = new Date().getTime().toString();
  a.click();
}

export const BASE_URL = import.meta.env.VITE_BASE_URL;

export const openTidio = () => {
  // @ts-ignore
  // @ts-nocheck
  window.tidioChatApi.show();
  // @ts-ignore
  // @ts-nocheck
  window.tidioChatApi.open();
};

export const closeTidio = () => {
  // @ts-ignore
  // @ts-nocheck
  window.tidioChatApi.close();
  // @ts-ignore
  // @ts-nocheck
  window.tidioChatApi.hide();
};

export {
  isEmail,
  isPassword,
  isWTCardPassword,
  isPhone,
  isPhoneAndEmail,
  initName,
} from './validate';
export {
  accountMasking,
  formatMinuteToString,
  formatMDHms,
  formatYMDHms,
  formatMDY,
  onlyNumberAllowed,
  formatAssetsNumber,
  formatCurrencyAmount,
  formatDecimal,
  isNull,
  pwdReg,
} from './format';
// export { getFingerprint, encryptedFingerprint } from './fingerprint';
export { NotifySuccess, NotifyWarn, NotifyError, NotifyCloseAll } from './notify';
export { Encrypt , Decrypt} from './jsencrypt';